package app.common.utils.dingtalk;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiUserListidRequest;
import com.dingtalk.api.request.OapiV2DepartmentGetRequest;
import com.dingtalk.api.request.OapiV2DepartmentListsubRequest;
import com.dingtalk.api.request.OapiV2UserGetRequest;
import com.dingtalk.api.response.OapiUserListidResponse;
import com.dingtalk.api.response.OapiV2DepartmentGetResponse;
import com.dingtalk.api.response.OapiV2DepartmentListsubResponse;
import com.dingtalk.api.response.OapiV2UserGetResponse;
import com.gitee.feizns.dynamic.Ex;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 钉钉部门相关接口
 * @author feizns
 * @since 2022/11/10
 */
@Slf4j
public class DepartUtils {

    /**
     * {@link Auth2Utils}
     */
    private final Auth2Utils auth2Utils;

    public DepartUtils(Auth2Utils auth2Utils) {
        this.auth2Utils = auth2Utils;
    }

    /**
     * 获取所有根部门
     * @return 所有根部门编号
     */
    public List<Long> getDepartments() {
        return getDepartments(1L);
    }

    /**
     * 获取所有的部门编号
     * @param parentId 父级部门编号（默认是1）
     * @return 部门编号列表
     */
    public List<Long> getDepartments(Long parentId) {
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/department/listsub");
        OapiV2DepartmentListsubRequest req = new OapiV2DepartmentListsubRequest();
        if ( parentId != null )
            req.setDeptId(parentId);
        OapiV2DepartmentListsubResponse rsp = Ex.tryCatch(() -> client.execute(req, auth2Utils.getAccessToken())).orElseThrow();
        if ( !rsp.isSuccess() )
            log.error("获取所有部门编号失败：" + rsp.getBody());
        return rsp.isSuccess() ? rsp.getResult()
                    .stream()
                    .map(OapiV2DepartmentListsubResponse.DeptBaseResponse::getDeptId)
                    .collect(Collectors.toList())
                : Collections.emptyList();
    }

    /**
     * 获取部门详情
     * @param deptId 部门编号
     * @return 部门信息
     */
    public OapiV2DepartmentGetResponse.DeptGetResponse getDepartment(Long deptId) {
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/department/get");
        OapiV2DepartmentGetRequest req = new OapiV2DepartmentGetRequest();
        req.setDeptId(deptId);
        req.setLanguage("zh_CN");
        OapiV2DepartmentGetResponse rsp = Ex.tryCatch(() -> client.execute(req, auth2Utils.getAccessToken())).orElseThrow();
        if ( !rsp.isSuccess() )
            log.error("获取部门详情失败：" + rsp.getBody());
        return rsp.getResult();
    }

    /**
     * 获取一个部门所有员工
     * @param deptId 部门编号
     * @return 返回部门所有用户编号
     */
    public List<String> getDepartmentUserIds(Long deptId) {
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/user/listid");
        OapiUserListidRequest req = new OapiUserListidRequest();
        req.setDeptId(deptId);
        OapiUserListidResponse rsp = Ex.tryCatch(() -> client.execute(req, auth2Utils.getAccessToken())).orElseThrow();
        if ( !rsp.isSuccess() )
            log.error("获取部门员工失败：" + rsp.getBody());
        return rsp.getResult().getUseridList();
    }

    @SneakyThrows
    public OapiV2UserGetResponse.UserGetResponse userGet(String userid) {
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/get");
        OapiV2UserGetRequest req = new OapiV2UserGetRequest();
        req.setUserid(userid);
        req.setLanguage(auth2Utils.getConfig().getLanguage());
        OapiV2UserGetResponse rsp = client.execute(req, auth2Utils.getAccessToken());
        if ( !rsp.isSuccess() )
            throw new RuntimeException(rsp.getBody());
        return rsp.getResult();
    }

    public static void main(String[] args) {

//        System.err.println(Arrays.toString(Thread.currentThread().getStackTrace()));
        //家校通讯录的部门信息拿不到？
//        getDepartment(59522675L);
        System.out.println();
//        System.out.println(getDepartment(59522675L));
//        System.out.println(getDepartmentUserIds(59522675L));
    }

}
